<!--公司领导人员配置-->
<template>
  <div class="app-container">
    <div class="container-menu">
      <el-button type="primary" @click="handleAdd" size="small">新增</el-button>
    </div>
    <div class="table-container">
      <vxe-table ref="tableRef" :row-config="rowConfig" :data="tableData" :seq-config="seqConfig" @row-dragend="rowDragendEvent">
        <vxe-column field="role" title="排序" drag-sort width="50"></vxe-column>
        <vxe-column type="seq" title="序号" width="50" align="center"></vxe-column>
        <vxe-column field="year" title="年份" width="60" align="center"></vxe-column>
        <vxe-column field="userName" title="领导姓名" width="80" align="center"></vxe-column>
        <vxe-column field="userId" title="登录账号" width="100" align="center"></vxe-column>
        <vxe-column field="departmentName" title="分管部门" min-width="70" show-overflow="title"></vxe-column>
        <vxe-column field="normativeTypeName" title="负责连带规范性动作类型" min-width="150" show-overflow="title"></vxe-column>
        <vxe-column field="grassrootsContactName" title="基层联络点" min-width="100" show-overflow="title"></vxe-column>
        <vxe-column field="previousLeadingUserName" title="往任领导" width="80" align="center"></vxe-column>
        <vxe-column
          field="whetherEnable"
          title="是否启用"
          width="80"
          align="center"
          :formatter="formatterWhetherEnable"
        ></vxe-column>
        <vxe-column field="action" title="操作" width="150" align="center">
          <template #default="{ row }">
            <vxe-button mode="text" status="primary" @click="editDetails(row)">编辑</vxe-button>
            <vxe-button mode="text" status="primary" @click="deletePageData({ id: row.id })">删除</vxe-button>
          </template>
        </vxe-column>
      </vxe-table>
      <el-pagination
        background
        :current-page="pageNumber"
        :page-sizes="[10, 20, 50, 100, 200]"
        :page-size="pageSize"
        layout="prev, pager, next, sizes, jumper, total"
        :total="total"
        @current-change="pageChange"
        @size-change="sizeChange"
      >
      </el-pagination>
    </div>
    <!--新增弹窗-->
    <el-dialog :title="formType === NEWLY_ADDED.type ? NEWLY_ADDED.title : EDIT.title" :visible.sync="dialogFormVisible">
      <jdf-increased-form
        ref="increaseForm"
        :configs="configs"
        :data="formData"
        :formAttrs="formAttrs"
        :all-fields-readonly="allFieldsReadonly"
        @select="selectOrg"
        :rules="rules"
      ></jdf-increased-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { first } from 'lodash-es';
import ResearchFormService from '@/api/domains/ResearchFormService';
import commonMixins from '@/mixins/commonMixins';
import { showErrorMsg } from '@/api/utils/pc-message';
import { getStorageInfo } from '@/api/utils/storage-util';
import listTableMixins from '@/mixins/listTableMixins';
import processFormCommonMixin from '@/views/procecss-form/processFormCommonMixin.js';
import configManagementMixins from '@/mixins/configManagementMixins.js';
import { WHETHER_ENABLE, DEFAULT_DATE } from '@/utils/constants.js';
const { ENABLED, DISABLED } = WHETHER_ENABLE;
const { DAY, MONTH } = DEFAULT_DATE;
const {
  deetsConfigDetail,
  delConfigDelete,
  getConfigPage,
  updConfigUpdate,
  addConfigSave,
  getSubjectManagePage,
  getContactPage,
  leadershipUpdateOrder,
} = new ResearchFormService();
export default {
  mixins: [processFormCommonMixin, listTableMixins, commonMixins, configManagementMixins],
  data() {
    return {
      //获取表格数据
      getTable: getConfigPage,
      //删除表格数据
      deleteList: delConfigDelete,
      //更新表格数据
      updateList: updConfigUpdate,
      //新增表格数据
      addList: addConfigSave,
      //排序表格
      sortList: leadershipUpdateOrder,
      //表单数据
      formData: {
        //年份
        year: dayjs().format('YYYY'),
        //序号
        sort: '',
        //领导姓名
        userName: '',
        //登录账号
        userId: '',
        //往任领导Id
        previousLeadingUserId: '',
        //往任领导姓名
        previousLeadingUserName: '',
        //分管部门
        departmentName: '',
        //负责连带规范性动作类型
        normativeTypeName: '',
        normativeType: '',
        //基层联络点
        grassrootsContactName: '',
        //是否启用
        whetherEnable: ENABLED,
      },
      //表单验证规则
      rules: {
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        year: [{ required: true, message: '请输入年份', trigger: 'blur' }],
        userName: [{ required: true, message: '请选择领导姓名', trigger: 'blur' }],
        normativeType: [{ required: true, message: '请选择负责连带规范性动作类型', trigger: 'blur' }],
        grassrootsContactName: [{ required: true, message: '请选择基层联络点', trigger: 'blur' }],
      },
      //表单配置项
      configs: [
        [
          {
            formElName: '年份',
            formElCode: 'year',
            editable: '1',
            colSpan: 24,
            elType: 'DatePicker',
            attrs: { type: 'year', format: 'yyyy年', valueFormat: 'yyyy' },
          },
        ],
        [
          {
            formElName: '领导姓名',
            formElCode: 'userName',
            editable: '1',
            colSpan: 24,
            elType: 'personOrOrg',
            visibleField: 'groupIdentityTreeVisible',
            treeAttrs: {
              groupCode: 'DY_TJZ_COMPANY_LEADER',
              identityId: getStorageInfo('identityId'),
              dialogTitle: '选择人员', //弹窗标题
              echoField: 'userName', //会显到input的字段
            },
            attrs: {
              placeholder: '请选择人员',
            },
          },
        ],
        [
          {
            formElName: '登录账号',
            formElCode: 'userId',
            editable: '0',
            colSpan: 24,
            elType: 'personOrOrg',
            attrs: { placeholder: '请选择人员' },
          },
        ],
        [
          {
            formElName: '分管部门',
            formElCode: 'departmentName',
            editable: '1',
            colSpan: 24,
            elType: 'personOrOrg',
            visibleField: 'groupOrgTreeVisible',
            treeAttrs: {
              groupCode: 'DY_HOT_DEPT', //部门字典
              identityId: getStorageInfo('identityId'),
              dialogTitle: '选择部门', //弹窗标题
              echoField: 'departmentInCharge', //会显到input的字段
              lazy: true, //是否懒加载
              multiple: true, //多选
            },
            attrs: {
              placeholder: '请选择部门',
            },
          },
        ],
        [
          {
            formElName: '负责连带规范性动作类型',
            formElCode: 'normativeType',
            editable: '1',
            colSpan: 24,
            elType: 'dialogTable',
            visibleField: 'dialogTableVisible',
            dialogTableAttrs: {
              dialogTitle: '选择动作类型',
              dialogTableColumns: [
                { type: 'selection', attrs: { 'reserve-selection': true } },
                { label: '动作类型', prop: 'specificRequirement', attrs: { 'show-overflow-tooltip': true } },
              ],
              selectKey: 'id',
              multipleSelect: true, //多选
              tableAttrs: { border: true },
              formatParam: {
                'format-list': 'records',
                'format-total': 'total',
                'format-number': 'page',
                'format-size': 'size',
              },
              dialogTablePaginationAttrs: {
                'current-page': 1,
                'page-size': 10,
                layout: 'prev, sizes, pager, next, jumper, total',
                total: 0,
                background: true,
                'page-sizes': [10, 20, 30],
              },
              searchMethod: this.getMmanagePage,
              showNameField: 'specificRequirement',
            },
            attrs: {
              placeholder: '请选择动作类型',
              type: 'textarea',
              rows: 3,
            },
          },
        ],
        [
          {
            formElName: '基层联络点',
            formElCode: 'grassrootsContactName',
            editable: '1',
            colSpan: 24,
            elType: 'dialogTable',
            visibleField: 'dialogTableVisible',
            dialogTableAttrs: {
              dialogTitle: '选择区县',
              dialogTableColumns: [
                { type: 'selection', attrs: { 'reserve-selection': true } },
                { label: '区县', prop: 'grassrootsContactName', attrs: { 'show-overflow-tooltip': true } },
              ],
              selectKey: 'id',
              multipleSelect: true, //多选
              tableAttrs: { border: true },
              formatParam: {
                'format-list': 'records',
                'format-total': 'total',
                'format-number': 'page',
                'format-size': 'size',
              },
              dialogTablePaginationAttrs: {
                'current-page': 1,
                'page-size': 10,
                layout: 'prev, sizes, pager, next, jumper, total',
                total: 0,
                background: true,
                'page-sizes': [10, 20, 30],
              },
              searchMethod: this.getGrassrootsContactName,
              showNameField: 'grassrootsContactName', // 输入框要展示的名称
            },
            attrs: {
              placeholder: '请选择基层联络点',
              type: 'textarea',
              rows: 3,
            },
          },
        ],
        [
          {
            formElName: '往任领导',
            formElCode: 'previousLeadingUserName',
            editable: '1',
            colSpan: 24,
            elType: 'personOrOrg',
            visibleField: 'groupIdentityTreeVisible',
            treeAttrs: {
              groupCode: 'DY_TJZ_COMPANY_LEADER',
              identityId: getStorageInfo('identityId'),
              dialogTitle: '选择人员', //弹窗标题
              echoField: 'previousLeadingUserName', //会显到input的字段
            },
            attrs: {
              placeholder: '请选择人员',
            },
          },
        ],
        [
          {
            formElName: '是否启用',
            formElCode: 'whetherEnable',
            editable: '1',
            colSpan: 24,
            elType: 'select',
            attrs: {
              clearable: false,
            },
            options: [
              {
                label: '是',
                value: ENABLED,
              },
              {
                label: '否',
                value: DISABLED,
              },
            ],
          },
        ],
        [
          {
            formElName: '排序',
            formElCode: 'sort',
            elType: 'number',
            editable: '1',
            colSpan: 24,
            attrs: {
              min: 1,
              placeholder: '请输入排序',
            },
          },
        ],
      ],
    };
  },
  methods: {
    /**
     * 获取区县数据
     * @param {Object} params 请求参数
     */
    async getGrassrootsContactName(params) {
      try {
        const {
          data: { data },
        } = await getContactPage(params);
        return data || [];
      } catch (error) {
        showErrorMsg(error);
      }
    },

    /**
     * 获取连带规范性动作类型
     * @param {Object} value 请求参数
     */
    async getMmanagePage(value) {
      try {
        const params = {
          ...value,
          year: this.formData.year,
        };
        const {
          data: { data },
        } = await getSubjectManagePage(params);
        return data || [];
      } catch (error) {
        showErrorMsg(error);
      }
    },

    /**
     * 获取详情
     * @param id 详情的id
     */
    async getDeetsConfigDetail({ id }) {
      try {
        const {
          data: { data },
        } = await deetsConfigDetail({ id });
        const { year, whetherEnable, normativeTypeName, leadershipGrassrootsContactVOS, leadershipNormativeTypeVOS } = data;
        const formData = {
          ...data,
          //年份回显格式转换
          year: dayjs().year(year).month(MONTH).date(DAY).format('YYYY-M-D'),
          //是否启用回显格式转换
          whetherEnable: whetherEnable ? ENABLED : DISABLED,
          normativeType: normativeTypeName,
          //基层联络点类型回显格式转换
          grassrootsContactNameSelected: leadershipGrassrootsContactVOS.map(({ grassrootsContactId, sort }) => ({
            id: grassrootsContactId,
            sort,
          })),
          //连带规范性动作类型回显格式转换
          normativeTypeSelected: leadershipNormativeTypeVOS.map(({ normativeTypeId, sort }) => ({
            id: normativeTypeId,
            sort,
          })),
        };
        Object.assign(this.formData, { ...formData });
      } catch (error) {
        showErrorMsg(error);
      }
    },

    /**
     * 选择领导姓名，填写领导工号
     * @param datas 选中的数据
     * @param echoField 回显字段
     */
    selectOrg(datas, echoField) {
      //当为分管部门选择框的时候，没有userName和loginName。或者选择框如果不做任何选择，first(datas)为undefined
      const { userName, loginName } = first(datas)?.userIdentityObj || {};
      switch (echoField) {
        case 'previousLeadingUserName':
          // 往任领导选择框
          Object.assign(this.formData, { previousLeadingUserName: userName, previousLeadingUserId: loginName });
          break;
        case 'userName':
          // 领导姓名选择框
          Object.assign(this.formData, { userName, userId: loginName });
          break;
        case 'departmentInCharge':
          // 分管部门选择框
          const { departmentName, departmentCode } = datas.reduce(
            ({ departmentName, departmentCode }, { name, id }, index) => {
              const delimiter = index ? ',' : '';
              return {
                departmentName: `${departmentName}${delimiter}${name}`,
                departmentCode: `${departmentCode}${delimiter}${id}`,
              };
            },
            { departmentName: '', departmentCode: '' },
          );
          Object.assign(this.formData, { departmentName, departmentCode });
        default:
          break;
      }
    },

    /**
     * 提交表单
     */
    handleSubmit() {
      const {
        id,
        userName,
        previousLeadingUserId,
        previousLeadingUserName,
        departmentName,
        userId,
        whetherEnable,
        grassrootsContactName,
        departmentCode,
        sort,
        year,
        grassrootsContactNameSelected,
        normativeTypeSelected,
        normativeType,
      } = this.formData;
      const yearDay = dayjs(year);
      // 当编辑的时候，年份如果没修改，时间格式不正确，需要改成年份字符串
      const newYear = yearDay.isValid() ? yearDay.year().toString() : year;
      const params = {
        id,
        userId,
        userName,
        //往任领导Id
        previousLeadingUserId,
        //往任领导姓名
        previousLeadingUserName,
        //负责连带规范性动作类型
        normativeTypeName: normativeType,
        //分管部门编号
        departmentCode,
        //分管部门
        departmentName,
        //是否启用
        whetherEnable,
        //基层联络点名称
        grassrootsContactName,
        sort,
        year: newYear,
        //基层联络点类型
        leadershipGrassrootsContactDTOS: grassrootsContactNameSelected.map(({ id, sort }) => ({
          grassrootsContactId: id,
          sort,
        })),
        //连带规范性动作类型
        leadershipNormativeTypeDTOS: normativeTypeSelected.map(({ id, sort }) => ({
          normativeTypeId: id,
          sort,
        })),
      };
      this.submitFormData(params);
    },

    /**
     * 重置表单
     */
    resetForm() {
      const resetData = {
        //id
        id: '',
        //领导姓名
        userName: '',
        //登录账号
        userId: '',
        //往任领导Id
        previousLeadingUserId: '',
        //往任领导姓名
        previousLeadingUserName: '',
        //分管部门
        departmentName: '',
        //负责连带规范性动作类型
        normativeTypeName: '',
        normativeType: '',
        //基层联络点
        grassrootsContactName: '',
        //是否启用
        whetherEnable: ENABLED,
        //排序
        sort: '',
        //年
        year: dayjs().format('YYYY'),
        //负责连带规范性动作类型
        normativeTypeSelected: [],
        //基层联络点类型
        grassrootsContactNameSelected: [],
      };
      Object.assign(this.formData, resetData);
    },
  },
};
</script>

<style scoped lang="scss">
@import '@/assets/style/configManagement.scss';
</style>
